package com.LCQ.crm.settings.service;

import com.LCQ.crm.exception.LoginException;
import com.LCQ.crm.settings.dao.DicTypeDao;
import com.LCQ.crm.settings.dao.DicValueDao;
import com.LCQ.crm.settings.dao.UserDao;
import com.LCQ.crm.settings.domain.DicType;
import com.LCQ.crm.settings.domain.DicValue;
import com.LCQ.crm.settings.domain.User;
import com.LCQ.crm.utils.MD5Util;
import com.LCQ.crm.utils.SqlSessionUtil;

import java.text.SimpleDateFormat;
import java.util.*;

/*
 * 用户登录验证
 * 1、username password
 * 2、expireTime  有效期
 * 3、lockState   锁定状态
 * 4、allowIps    允许访问的ip
 * */
public class UserServiceImpl implements UserService {
    private UserDao userDao = SqlSessionUtil.getSqlSession().getMapper(UserDao.class);
    private DicTypeDao dicTypeDao = SqlSessionUtil.getSqlSession().getMapper(DicTypeDao.class);
    private DicValueDao dicValueDao = SqlSessionUtil.getSqlSession().getMapper(DicValueDao.class);
    @Override
    public User login(String userName, String password, String addr) throws LoginException {
        String pwdMD5 = MD5Util.getMD5(password);
        Map userBaseInfo = new HashMap();
        userBaseInfo.put("userName",userName);
        userBaseInfo.put("password",pwdMD5);
        User user = userDao.login(userBaseInfo);
        if(user==null){
            throw new LoginException("用户名或密码错误");
        }

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String newDate = simpleDateFormat.format(new Date());
        if(newDate.compareTo(user.getExpireTime())>0){
            throw new LoginException("用户已过期");
        }

        if("1".equals(user.getLockState())){
            throw new LoginException("用户已锁");
        }

        if(!user.getAllowIps().contains(addr)){
            throw new LoginException("IP地址非法");
        }
        return user;
    }

    @Override
    public List<Map> selectAll() {
        return userDao.selectAll();
    }

    @Override
    public Map<String, List<DicValue>> getDic() {
        List<DicType> listDType = dicTypeDao.getAll();
        Iterator<DicType> it = listDType.iterator();
        Map<String, List<DicValue>> map = new HashMap<>();
        while(it.hasNext()){
            DicType dicType = it.next();
            List<DicValue> listDValue = dicValueDao.getByTypeCode(dicType.getCode());
            map.put(dicType.getCode(),listDValue);
        }
        return map;
    }
}
